package com.market.cash.ui.fragment

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.market.cash.R
import com.market.cash.databinding.CashStepSelfieBinding
import com.market.cash.http.ApiService
import com.market.cash.http.ApiService.addCommonParams
import com.market.cash.pro.ProFragment
import com.market.cash.ui.activity.CameraSelfieActivity
import com.market.cash.ui.activity.StepsActivity
import com.market.cash.utils.CashRootImageUtil
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.log.CashRootLog
import com.market.cash.utils.permission.OnPermissionCallback
import com.market.cash.utils.permission.Permission
import com.market.cash.utils.permission.XXPermissions
import org.json.JSONObject
import java.io.File

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/23 13:40
 * @Annotation：认证流程 - 自拍照
 */
class StepSelfieFragment(): ProFragment() {
    lateinit var binding: CashStepSelfieBinding
    private var stepItem: JSONObject? = null

    //本地预览地址
    private var faceImgPath = ""
    //拍摄的头像地址
    private var faceImgUrl = ""

    constructor(stepItem: JSONObject): this(){
        this.stepItem = stepItem
    }

    override fun getCashRootRootView(inflater: LayoutInflater): View {
        binding = CashStepSelfieBinding.inflate(inflater)
        return binding.root
    }

    override fun initCashRootView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#00000000"))
        showCashRootSelfieBeforeView()
        if (stepItem != null){
            binding.textStepTitle.text = stepItem!!.optString("showTitle")
        }
    }

    override fun initCashRootListener() {
        binding.imgView.setOnClickListener {
            if (faceImgPath.isEmpty()){
                binding.btnStartOrSubmit.callOnClick()
            }
        }
        //删除照片
        binding.imgRemove.setOnClickListener {
            if (faceImgPath.isNotEmpty()){
                addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_STEP_SELFIE_REMOVE_PHOTO,faceImgUrl)
                //删除图片
                val imgFile = File(faceImgPath)
                if (imgFile.isFile){
                    imgFile.delete()
                }
            }
            faceImgPath = ""
            faceImgUrl = ""
            showCashRootSelfieBeforeView()
        }
        //提交
        binding.btnStartOrSubmit.setOnClickListener {
            //开始人脸拍照
            if (faceImgUrl.isEmpty()){
                if (XXPermissions.isGranted(requireContext(), Permission.CAMERA)){
                    openCashRootSelfieCamera()
                } else {
                    XXPermissions.with(requireContext())
                        // 申请多个权限
                        .permission(Permission.CAMERA)
                        .request(object: OnPermissionCallback {
                            override fun onGranted(p0: MutableList<String>, p1: Boolean) {
                                addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_PERMISSION_SYSTEM_AGREE, Permission.CAMERA)
                                openCashRootSelfieCamera()
                            }
                            override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                                addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_PERMISSION_SYSTEM_DENY, Permission.CAMERA)
                                XXPermissions.startPermissionActivity(context!!,permissions)
                            }
                        })
                }
                return@setOnClickListener
            }
            //提交
            val params = JSONObject().addCommonParams().apply {
                put("path", ApiService.API_PATH.CASHROOT_API_OCR_INFO_PATH)
                put("cardType","FACE")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
                put("faceImgUrl",faceImgUrl)//人脸图片
            }
            val act = getAct() as StepsActivity
            act.onCashRootSubmitAction(params)

            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_STEP_SELFIE_CONFIRM_SUBMIT)
        }
    }

    override fun initCashRootData() {
    }

    /**
     * 人脸拍照
     */
    private val faceCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                val faceImgPath = result.data!!.getStringExtra("imgLocalPath").toString()
                CashRootLog.e(">>>>>>>>>face info ：$faceImgPath")
                val imgLocalPath = result.data!!.getStringExtra("imgLocalPath").toString()
                val imgUrl = result.data!!.getStringExtra("imgUrl").toString()
                showCashRootSelfieAfterView(imgLocalPath,imgUrl)
            }
        }
    }

    /**
     * 显示未拍照View
     */
    private fun showCashRootSelfieBeforeView(){
        binding.imgView.setImageResource(R.mipmap.cash_selfie_default_avater)
        binding.imgView.setBorderWidth(resources.getDimension(com.lib.base.R.dimen.qb_px_0))
        binding.imgRemove.visibility = View.INVISIBLE
        binding.btnStartOrSubmit.text = getString(R.string.step_selfie_take)
    }

    /**
     * 显示拍照之后的View
     */
    private fun showCashRootSelfieAfterView(imgPath: String,imgUrl: String){
        faceImgPath = imgPath
        faceImgUrl = imgUrl
        CashRootImageUtil.instance.loadImageUrl(requireContext(),binding.imgView,faceImgPath)
        binding.imgView.setBorderWidth(resources.getDimension(com.lib.base.R.dimen.qb_px_12))
        binding.imgRemove.visibility = View.VISIBLE
        binding.btnStartOrSubmit.text = getString(R.string.step_selfie_submit)
    }

    /**
     * 打开相机
     */
    private fun openCashRootSelfieCamera(){
        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_STEP_SELFIE_START_TAKE)
        faceCameraResultLauncher.launch(Intent(context, CameraSelfieActivity::class.java))
    }

    override fun onStart() {
        super.onStart()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_STEP_SELFIE_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_STEP_SELFIE_END)
    }
}